<?php

class TicketsController extends Controller
{
    public $layout='//layouts/column2';
    public $totalpages=1;
    public $totalrecords=1;
    public $currentpage=1;
    public $orderfield=1;
    public $order=1;
    public $numofrecords=1;
    
    
    public function actionview_system()
	{
	   
		$model=new Systems;
        $sys_category=CActiveRecord::model("Systemcategories")->findAllBySql("select * from systemcategories where status=1 and is_deleted=0",array());
        $sys_categoryarr=$this->getRevisedArray($sys_category);
        
        $producttype=CActiveRecord::model("Producttypes")->findAllBySql("select * from producttypes where status=1 and is_deleted=0",array());
        $producttypearr=$this->getRevisedArray($producttype);
        
        $systemConfigure=array();
        if(isset($_POST['edit_id']) && $_POST['edit_id']>0)
        {
            	$paramsarr=array("sys_id"=>$_POST['edit_id']);
				$systemConfigure = Yii::app()->db->createCommand()
	            ->select('*')
	            ->from('systemconfigurations')
	            ->where('system_id=:sys_id order by id asc', $paramsarr)
	            ->queryAll();
		}
        else
        {
            $this->redirect('index.php?r=tickets/index');
        }
		
        if(isset($_POST['edit_id']) && $_POST['edit_id']>0)
        {
            $model=Systems::model()->findByPk($_POST['edit_id']); 
            
            $model=$this->getSingleRevisedArray($model);
           
           
        } 
		
        
			$this->render('view_system',array(
				'datainfo'=>$model,
				'syscat'=>$sys_categoryarr,
				'producttype'=>$producttypearr,
				'system_configure'=>$systemConfigure
			));
		
	}
	
    public function actionajax_new_ticket()
	{
		$countsql=Tickets::model()->findAllBySql("select id,ecode from tickets where ticket_status=:ticket_status",array("ticket_status"=>'Created'));
		$wholearr=$this->getRevisedArray($countsql);
        echo $count_num= $this->totalrecords=count($countsql);
        die;
    }	
    public function actionreply_ticket()
    {
		$model=new Tickets;
        
		if(isset($_POST['Records']))
		{
			if(isset($_POST['edit_id']) && $_POST['edit_id']>0)
            {
            	
				$model=Tickets::model()->findByPk($_POST['edit_id']);
                $model->resolved_date=time();
                $model->ticket_status=$_POST['Records']['ticket_status'];
                $model->resolver_description=$_POST['Records']['resolver_description'];
                
    		    $model->resolved_by=Yii::app()->session['User_Name'];
                $operatemsg="updat";
			}
            
		     
            	if($model->save())
	            {
	            	
					$logarr=array("performed_by"=>Yii::app()->session['Login_User'],"table_name"=>"tickets","opt_type"=>"Update","log_date"=>time(),"description"=>" Updated records on ticket number ".$_POST['ticket_no'],"updated_table_id"=>$_POST['edit_id']);
	                
	            	$command = Yii::app()->db->createCommand();
                    $command->reset();
                    $result=$command->insert('log',$logarr);
                    
                    ############################# doing changes in employee tickets table ######################
                    $upd_empinfo= "update tickets set ticket_status=:changedstatus,resolved_by=:resolved_by,resolved_date=:resolved_date,creator_seen_status=:seen_status,resolver_comment=:desc where ticket_no=:tick_no";
					$command = Yii::app()->db1->createCommand($upd_empinfo);
					$command->execute( array("changedstatus"=>$_POST['Records']['ticket_status'],"resolved_by"=>Yii::app()->session['User_Name'],'resolved_date'=>time(),"seen_status"=>'Unseen',"desc"=>$_POST['Records']['resolver_description'],"tick_no"=>$_POST['ticket_no']));
                    
	                Yii::app()->session['msg'] = "Records ".$operatemsg."ed successfully.";
	                Yii::app()->session['msg_type']="success";
	                
					$this->redirect(array('index'));
	            }
	            else
	            {
	                Yii::app()->session['msg'] = "There is an error in ".$operatemsg."ing Records.";
	                Yii::app()->session['msg_type']="error";
	                $this->redirect(array('index'));
	            }
            
            
		}
        
        if(isset($_POST['edit_id']) && $_POST['edit_id']>0)
        {
        	$model=Tickets::model()->findAllBySql("select * from tickets where id=:id",array("id"=>$_POST['edit_id']));
           	$modelarr=$this->getRevisedArray($model);
           
           ################### Trying to update on employee_db ticket table #####################
        	$check_query=Yii::app()->db1->createCommand()
		            ->select('count(*) as num')
		            ->from('tickets')
		            ->where('ticket_status=:creatstat and ticket_no=:tick_no', array("creatstat"=>'Created',"tick_no"=>$modelarr[0]['ticket_no']))
		            ->queryAll();
			
			if($check_query[0]['num']!=0)
			{
				$upd_emp= "update tickets set ticket_status=:viewstat,resolved_by=:resolved_by,resolved_date=:resolved_date,creator_seen_status=:seen_status where ticket_no=:tick_no";
				$command = Yii::app()->db1->createCommand($upd_emp);
				$command->execute( array("viewstat"=>'Viewed',"resolved_by"=>Yii::app()->session['User_Name'],'resolved_date'=>time(),"seen_status"=>'Unseen',"tick_no"=>$modelarr[0]['ticket_no']));
			}
			
			
        	################### Updating on stock ticket table #####################
        	$upd_stock = "update tickets set ticket_status=:viewstat,resolved_by=:resolved_by,resolved_date=:resolved_date where ticket_no=:tick_no";
			$command = Yii::app()->db->createCommand($upd_stock);
			$command->execute( array("viewstat"=>'Viewed',"resolved_by"=>Yii::app()->session['User_Name'],'resolved_date'=>time(),"tick_no"=>$modelarr[0]['ticket_no']));
								
           
          	$this->render('reply_ticket',array(
				'datainfo'=>$modelarr,
			));
        } 
        else
        {
		  $this->redirect('index.php?r=tickets/index');
        }
	}
    public function actionview_ticket()
	{
	   
		if(isset($_POST['edit_id']) && $_POST['edit_id']>0)
        {
        	$model=Tickets::model()->findAllBySql("select * from tickets where id=:id",array("id"=>$_POST['edit_id']));
           	$modelarr=$this->getRevisedArray($model);
           
           ################### Trying to update on employee_db ticket table #####################
        	$check_query=Yii::app()->db1->createCommand()
		            ->select('count(*) as num')
		            ->from('tickets')
		            ->where('ticket_status=:creatstat and ticket_no=:tick_no', array("creatstat"=>'Created',"tick_no"=>$modelarr[0]['ticket_no']))
		            ->queryAll();
			
			if($check_query[0]['num']!=0)
			{
				$upd_emp= "update tickets set ticket_status=:viewstat,resolved_by=:resolved_by,resolved_date=:resolved_date,creator_seen_status=:seen_status where ticket_no=:tick_no";
				$command = Yii::app()->db1->createCommand($upd_emp);
				$command->execute( array("viewstat"=>'Viewed',"resolved_by"=>Yii::app()->session['User_Name'],'resolved_date'=>time(),"seen_status"=>'Unseen',"tick_no"=>$modelarr[0]['ticket_no']));
			}
			
			
        	################### Updating on stock ticket table #####################
        	$upd_stock = "update tickets set ticket_status=:viewstat,resolved_by=:resolved_by,resolved_date=:resolved_date where ticket_no=:tick_no";
			$command = Yii::app()->db->createCommand($upd_stock);
			$command->execute( array("viewstat"=>'Viewed',"resolved_by"=>Yii::app()->session['User_Name'],'resolved_date'=>time(),"tick_no"=>$modelarr[0]['ticket_no']));
								
           
          	$this->render('view_ticket',array(
				'datainfo'=>$modelarr,
			));
        } 
        else
        {
		  $this->redirect('index.php?r=tickets/index');
        }
	}
	public function actionDelete()
	{
		/*
		$this->loadModel($_POST['delete_id'])->delete();
        Yii::app()->session['msg'] = "Records deleted successfully.";
        Yii::app()->session['msg_type']="success";
        $this->redirect(array("index"));
		*/
		$model=Tickets::model()->findByPk($_POST['delete_id']);
        
        $model->is_deleted=1;
	    $model->updated_by=Yii::app()->session['Login_User'];
        $model->update_date=time();
		//$this->loadModel($_POST['delete_id'])->delete();
        if($model->save())
        {
            Yii::app()->session['msg'] = "User deleted successfully.";
            Yii::app()->session['msg_type']="success";
            
            if(isset($model['username']))
            {
                $command = Yii::app()->db->createCommand();
                $command->reset();
                
                //maintaining log values
                $logarr=array("performed_by"=>Yii::app()->session['Login_User'],"table_name"=>"tickets","opt_type"=>"Delete","log_date"=>time(),"description"=>" deleted user ".$model['username'],"updated_table_id"=>$_POST['delete_id']);
                            
                $result=$command->insert('log',$logarr);
            } 
        }    
        $this->redirect(array("index"));
	}
	public function actionDashboard()
	{
		//$this->redirect(array("dashboard"));
		$this->render('dashboard',array());
		
	}
	public function actionDeleteall()
	{
	   /*
	    $idarr=explode(",",$_POST['delete_ids']);
        for($i=0;$i<count($idarr);$i++)
        {
		  $this->loadModel($idarr[$i])->delete();
        }
        Yii::app()->session['msg'] = "All Selected Tickets deleted successfully.";
        Yii::app()->session['msg_type']="success";
        $this->redirect(array("index"));
		*/
		$idarr=explode(",",$_POST['delete_ids']);
        for($i=0;$i<count($idarr);$i++)
        {
            $model=Tickets::model()->findByPk($idarr[$i]);
            
            
            $model->is_deleted=1;
    	    $model->updated_by=Yii::app()->session['Login_User'];
            $model->update_date=time();
        
            //$this->loadModel($idarr[$i])->delete();
            
            if($model->save())
            {
                if(isset($model['username']))
                {
                    $command = Yii::app()->db->createCommand();
                    $command->reset();
                    
                    //maintaining log values
                    $logarr=array("performed_by"=>Yii::app()->session['Login_User'],"table_name"=>"tickets","opt_type"=>"Delete","log_date"=>time(),"description"=>" deleted user ".$model['username'],"updated_table_id"=>$idarr[$i]);
                                
                    $result=$command->insert('log',$logarr);
                }
            }
        }
        Yii::app()->session['msg'] = "All Selected Tickets deleted successfully.";
        Yii::app()->session['msg_type']="success";
        $this->redirect(array("index"));
	}

	/**
	 * This is the default 'index' action that is invoked
	 * when an action is not explicitly requested by Tickets.
	 */
	public function actionIndex()
	{
		$orderfield="id";
        $order="desc";
        $pageno=1;
        $recordsperpage=$this->recordsperpage;
        
        if(isset($_POST['orderfield']) && trim($_POST['orderfield'])!="")
        {
            $orderfield=$_POST['orderfield'];
        }
        if(isset($_POST['order']) && trim($_POST['order'])!="")
        {
            $order=$_POST['order'];
        }
        if(isset($_POST['pageno']) && trim($_POST['pageno'])!="")
        {
            $pageno=$_POST['pageno'];
        }
        if(isset($_POST['numofrecords']) && trim($_POST['numofrecords'])!="")
        {
            $recordsperpage=$_POST['numofrecords'];
        }
        if($pageno<1)
        {
            $pageno=1;
        }
        
        $query="from tickets ";
        $paramsarr=array();
        
        if(isset($_POST['searchtext']) && trim($_POST['searchtext'])!="")
        {
            $query.=" where LOWER(ticket_no) like :ticket_no";
            $paramsarr[":ticket_no"]=strtolower(trim("%".$_POST['searchtext'])."%");
        }
        
        $this->numofrecords=$recordsperpage;
        $countsql=Tickets::model()->findAllBySql("select id ".$query,$paramsarr);
        $this->totalrecords=count($countsql);
        $this->totalpages=ceil($this->totalrecords/$this->numofrecords);
        $this->orderfield=$orderfield;
        $this->order=$order;
        $this->currentpage=$pageno;
        
        
        if($this->totalpages<=0)
        {
            $this->totalpages=1;
        }
        
        if($pageno>$this->totalpages)
        {
            $pageno=$this->totalpages;
        }
        
        $ticketsdata=Tickets::model()->findAllBySql("select * ".$query." order by ".$orderfield." ".$order." limit ".($pageno-1)*$this->numofrecords.", ".$this->numofrecords,$paramsarr);
        $ticketssarr=$this->getRevisedArray($ticketsdata);
        
        //print_r($Ticketssarr);
        //die();
		$this->render('index',array(
			'ticketsdata'=>$ticketssarr
		));
	}

	/**
	 * This is the action to handle external exceptions.
	 */
	public function actionError()
	{
	   	if($error=Yii::app()->errorHandler->error)
		{
			if(Yii::app()->request->isAjaxRequest)
			{
			     echo $error['message'];
            }
			else
			{
			    $this->render('error', $error);
            }
		}
	}
	public function loadModel($id)
	{
		$model=Tickets::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}
    
    
}


?>